package at.ac.tuwien.swa.sparrow.server.conf

import at.ac.tuwien.swa.sparrow.server.controller.{ClientController, PeerController}
import at.ac.tuwien.swa.sparrow.server.{ClientService, PeerService}
import at.ac.tuwien.swa.sparrow.util.MappingJerksonHttpMessageConverter
import com.fasterxml.jackson.databind.SerializationFeature
import javax.inject.Inject
import org.springframework.context.annotation.{Bean, Configuration, ComponentScan}
import org.springframework.http.MediaType
import org.springframework.http.converter.HttpMessageConverter
import org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean
import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter
import org.springframework.web.servlet.config.annotation.{WebMvcConfigurerAdapter, EnableWebMvc}

@ComponentScan(value = Array("at.ac.tuwien.swa"))
@Configuration
@EnableWebMvc
class SpringConfig extends WebMvcConfigurerAdapter {

	@Inject var clientController: ClientController = _
	@Inject var peerController: PeerController = _

	@Bean def peerService: HttpInvokerServiceExporter = {
		val factoryBean = new HttpInvokerServiceExporter()
		factoryBean.setService(peerController)
		factoryBean.setServiceInterface(classOf[PeerService])
		factoryBean.afterPropertiesSet()
		factoryBean
	}

	@Bean def clientService: HttpInvokerServiceExporter = {
		val factoryBean = new HttpInvokerServiceExporter()
		factoryBean.setService(clientController)
		factoryBean.setServiceInterface(classOf[ClientService])
		factoryBean.afterPropertiesSet()
		factoryBean
	}

	@Bean def objectMapper() = {
		val factoryBean = new Jackson2ObjectMapperFactoryBean()
		factoryBean.setFeaturesToEnable(SerializationFeature.WRAP_ROOT_VALUE)
		factoryBean.afterPropertiesSet()
		factoryBean.getObject
	}

	override def configureMessageConverters(converters: java.util.List[HttpMessageConverter[_]]) {
		converters.add(new MappingJerksonHttpMessageConverter[AnyRef](MediaType.APPLICATION_JSON))
	}

}
